import express from 'express';
import { Favorite } from '../../modal/index'; // 数据库实体类
import { statusList, sequelizeStatus } from '../../common/status'; // 状态码对照
import { checkPermission, aesEncrypt } from '../../utils/utils'; // 工具类

const router = express.Router();
const minLevel = 0; // 允许调用接口的最低等级

router.post('/', async function (Request, Response, next) {
  // Favorite .Modal.sync();
  let param = Request.body
  // 权限校验
  await checkPermission(Request, Response, minLevel).then(res => {
    param.userId = res.id
  })
  if (param.favorite) {
    if (!param.goodsId) {
      Response.status(300).send({ message: "商品信息为空，请稍后再试" });
    }
    // 收藏
    Favorite.Modal.create(param).then(res => {
      if (res && res.id) {
        Response.json({
          data: "",
          message: "success"
        });
      } else {
        Response.status(300).send({ message: "添加收藏失败" });
      }
    }).catch(err => {
      console.log(err)
      Response.status(500).send({ message: sequelizeStatus[err.name] || statusList[500] || err.name });
    });
  } else {
    if (!param.goodsId) {
      Response.status(300).send({ message: "商品信息为空，请稍后再试" });
    }
    // 取消收藏
    Favorite.Modal.destroy({
      where: {
        userId: param.userId,
        goodsId: param.goodsId,
      }
    }).then(res => {
      if (res === 1) {
        Response.json({
          data: "",
          message: "success"
        });
      } else {
        Response.status(300).send({ message: "取消收藏失败，该收藏记录不存在" });
      }
    }).catch(err => {
      console.log(err)
      Response.status(500).send({ message: sequelizeStatus[err.name] || statusList[500] || err.name });
    });
  }
});

module.exports = router;